package com.example.itensyuan0609.fragment;


import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListView;

import androidx.fragment.app.Fragment;

import com.example.itensyuan0609.MyNewsAdapter;
import com.example.itensyuan0609.MyService;
import com.example.itensyuan0609.NewsActivity;
import com.example.itensyuan0609.R;
import com.example.itensyuan0609.bin.MyBean;

import java.util.List;


public class OneFragment extends Fragment {

    static List<MyBean.ResultBean.DataBean> list;
    ListView lv;
    NewsReceiver newsReceiver;
    String url;

    public OneFragment() {

    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View v = inflater.inflate(R.layout.fragment_one, container, false);
        lv = v.findViewById(R.id.lv);
        initService();
        // Inflate the layout for this fragment

        return v;
    }

    public void initService() {
        Intent intent = new Intent(getContext(), MyService.class);
        getContext().startService(intent);
        newsReceiver = new NewsReceiver();
        IntentFilter filter = new IntentFilter();
        filter.addAction(MyService.ACTION);
        getContext().registerReceiver(newsReceiver, filter);
        lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                Intent intent1 = new Intent(getContext(), NewsActivity.class);
                url = list.get(i).getUrl();
                intent1.putExtra("url", url);
                startActivity(intent1);
            }
        });
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        getContext().unregisterReceiver(newsReceiver);
    }

    public class NewsReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            if (MyService.ACTION.equals(intent.getAction())) {
                MyBean myBean = (MyBean) intent.getSerializableExtra("myBean");
                list = myBean.getResult().getData();
                for (int i = 0; i < list.size(); i++) {
                    MyBean.ResultBean.DataBean dataBean = list.get(i);
                    if (dataBean.getThumbnail_pic_s03() == null) {
                        dataBean.setType(0);
                    } else {
                        dataBean.setType(1);
                    }

                }
                lv.setAdapter(new MyNewsAdapter(list, getContext()));
            }
        }
    }

}
